//
//  LoginViewController.m
//  NOAHWM
//
//  Created by Ryan on 13-5-22.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "LoginViewController.h"
#import "NSString+IPAddress.h"
#import "NSString+MD5.h"
#import "JSON.h"
#import "NYMemberCenterDataManager.h"
#import "NSString+ContainChinese.h"
#import "RegisterViewController.h"
#import "ForgetViewController.h"
#import "MemberChosenViewController.h"

#define kLVCLoginDownloaderKey @"LVCLoginDownloaderKey"

@interface LoginViewController ()

@end

@implementation LoginViewController

@synthesize usernameField,passwordField,loginButton;
@synthesize kefuButton;

#pragma mark - Private methods
- (NSString *)checkFieldValid
{
    //username长度1-50
    //password: 6-50
    if(usernameField.text.length < 1)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000001E"],@"用户名"];
    else if(usernameField.text.length > 50)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000002E"],@"用户名"];
    else if([NSString containChinese:usernameField.text])
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000003E"],@"用户名"];
    else if(passwordField.text.length < 6)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000001E"],@"密码"];
    else if(passwordField.text.length > 50)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000002E"],@"密码"];
    return nil;
}


#pragma mark - IBAction methods
- (IBAction)loginButtonClicked:(id)sender
{
    [self resignAllField];
    
    NSString *checkString = [self checkFieldValid];
    if(checkString)
    {
        [[RYHUDManager sharedManager] showWithMessage:checkString customView:nil hideDelay:2.f];
    }
    else
    {
        [NYMemberCenterDataManager sharedManager].loginMember.phoneNum = nil;
//        [NYMemberCenterDataManager sharedManager].loginMember.dynPwd = self.passwordField.text;
        //调用登录接口，获取会员相关信息
        NSString *md5UserName = [NSString md5HexDigest:self.usernameField.text];
        NSString *md5Password = [NSString md5HexDigest:self.passwordField.text];
        NSString *ipAddress = [NSString getIPAddress];
        
        NSString *subLoginUrl = [NSString stringWithFormat:kLoginUrl,@"jsonp",md5UserName,md5Password,ipAddress];
        subLoginUrl = [subLoginUrl stringByAppendingString:@"app000001"];
        NSString *loginUrl = [NSString stringWithFormat:@"%@%@",kServerAddress,subLoginUrl];
        loginUrl = [loginUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:loginUrl delegate:self purpose:kLVCLoginDownloaderKey];
        [[RYHUDManager sharedManager] startedNetWorkActivityWithText:@"登录中..."];
    }
}

- (IBAction)registerButtonClicked:(id)sender
{
    [self resignAllField];
    RegisterViewController *rvc = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:rvc animated:YES];
    [rvc release];
}
- (IBAction)changePwdButtonClicked:(id)sender
{
    [self resignAllField];
    ForgetViewController *fvc = [[ForgetViewController alloc] init];
    [self.navigationController pushViewController:fvc animated:YES];
    [fvc release];
}

#pragma mark - BaseViewController methods
- (void)leftItemTapped
{
    [self resignAllField];
    [self.navigationController dismissModalViewControllerAnimated:YES];
}

#pragma mark - UIViewController methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNaviTitle:@"登录"];
    [self setLeftNaviItemWithTitle:nil imageName:@"Icon_Back"];
    [self setRightNaviItemWithTitle:nil imageName:nil];
    
    [self.kefuButton setTitle:[NSString stringWithFormat:@"客服热线：%@",[NYMemberCenterDataManager sharedManager].loginMember.custom_service_phone] forState:UIControlStateNormal];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.isViewLoaded && !self.view.window)
    {
        [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:kLVCLoginDownloaderKey];
        self.view = nil;
        self.usernameField = nil;
        self.passwordField = nil;
        self.loginButton = nil;
        self.kefuButton = nil;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:kLVCLoginDownloaderKey];
    self.usernameField = nil;
    self.passwordField = nil;
    self.loginButton = nil;
    self.bodyView = nil;
    self.phoneCallAs = nil;
    self.kefuButton = nil;

}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:kLVCLoginDownloaderKey];
    [kefuButton release];
    [usernameField release];
    [passwordField release];
    [loginButton release];
    [bodyView release];
    [phoneCallAs release];

    [super dealloc];
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    NSDictionary *dict = [str JSONValue];
    if([[dict objectForKey:@"result"] isEqualToString:@"1"])
    {
        [[RYHUDManager sharedManager] stoppedNetWorkActivity];
        [NYMemberCenterDataManager sharedManager].memberRoles = [NSMutableArray array];
        NSArray *list = [dict objectForKey:@"list"];
        for(NSDictionary *dictUser in list)
        {
            NYMember *nym = [[NYMember alloc] init];
            nym.accountId = [dictUser objectForKey:@"ACCOUNT_ID"];
            nym.accountName = [dictUser objectForKey:@"ACCOUNT_NAME"];
            nym.memberCardType = [dictUser objectForKey:@"MEMBER_CARD_TYPE"];
            nym.recordTypeName = [dictUser objectForKey:@"RECORD_TYPE_NAME"];
            nym.status = [dictUser objectForKey:@"STATUS"];
            nym.loginLogId = [dictUser objectForKey:@"login_log_id"];
            nym.is_gesture_password = [dictUser objectForKey:@"IS_GESTURE_PASSWORD"];
            nym.is_auth = [dictUser objectForKey:@"IS_AUTH"];
            [[NYMemberCenterDataManager sharedManager].memberRoles addObject:nym];
            [nym release];
//            NSDictionary *dictUser = [list objectAtIndex:0];
//            [NYMemberCenterDataManager sharedManager].loginMember.accountId = [dictUser objectForKey:@"ACCOUNT_ID"];
//            [NYMemberCenterDataManager sharedManager].loginMember.accountName = [dictUser objectForKey:@"ACCOUNT_NAME"];
//            [NYMemberCenterDataManager sharedManager].loginMember.memberCardType = [dictUser objectForKey:@"MEMBER_CARD_TYPE"];
//            [NYMemberCenterDataManager sharedManager].loginMember.recordTypeName = [dictUser objectForKey:@"RECORD_TYPE_NAME"];
//            [NYMemberCenterDataManager sharedManager].loginMember.status = [dictUser objectForKey:@"STATUS"];
//            [NYMemberCenterDataManager sharedManager].loginMember.loginLogId = [dictUser objectForKey:@"login_log_id"];
//            [NYMemberCenterDataManager sharedManager].loginMember.is_gesture_password = [dictUser objectForKey:@"IS_GESTURE_PASSWORD"];
//            [NYMemberCenterDataManager sharedManager].loginMember.is_auth = [dictUser objectForKey:@"IS_AUTH"];
        }
        if([NYMemberCenterDataManager sharedManager].memberRoles.count == 1)
        {
            //该用户只有一个角色，直接进入
            [NYMemberCenterDataManager sharedManager].loginMember = [[NYMemberCenterDataManager sharedManager].memberRoles objectAtIndex:0];
            //重新load左菜单
            [[NSNotificationCenter defaultCenter] postNotificationName:kUserChangeNotification object:nil];
            //修改有菜单中“申请认证”按钮状态
            [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshApplyAuthNotificaiton object:nil];
            //重新获取个人信息
            [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshPersonalInfoNotification object:nil];
            [self.navigationController dismissModalViewControllerAnimated:YES];
        }
        else
        {
            //该用户有两个角色，进入角色选择页
            MemberChosenViewController *mcvc = [[MemberChosenViewController alloc] init];
            mcvc.isFromLogin = YES;
            [self.navigationController pushViewController:mcvc animated:YES];
            [mcvc release];
        }
    }
    else
    {
        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
    }
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}

#pragma mark - UI控制，by Charles
@synthesize bodyView;
@synthesize phoneCallAs;

- (UIActionSheet *)phoneCallAs
{
    if(nil == phoneCallAs)
    {
        phoneCallAs = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"咨询客服", nil];
    }
    return phoneCallAs;
}

//取消键盘
- (void)resignAllField
{
    [self.usernameField resignFirstResponder];
    [self.passwordField resignFirstResponder];
}

- (IBAction)hideKeyboardButtonClick:(id)sender
{
    [self resignAllField];
}

- (IBAction)kefuButtonClick:(id)sender
{
    [self resignAllField];
    [self.phoneCallAs showInView:self.view];
}

- (void)keyboardWillShow:(NSNotification *)note
{
    // get keyboard size and loctaion
	CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
	// set views with new info
    self.bodyView.contentSize = CGSizeMake(self.bodyView.frame.size.width, 350.f);
	self.bodyView.frame = CGRectMake(self.bodyView.frame.origin.x, self.bodyView.frame.origin.y, self.bodyView.frame.size.width,
                                     self.view.frame.size.height - keyboardBounds.size.height - self.bodyView.frame.origin.y);
	[UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)note
{
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
	
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
	// set views with new info
	self.bodyView.frame = CGRectMake(self.bodyView.frame.origin.x, self.bodyView.frame.origin.y, self.bodyView.frame.size.width, 350.f);
    self.bodyView.contentSize = CGSizeMake(self.bodyView.frame.size.width, 350.f);
	[UIView commitAnimations];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if(textField == self.usernameField)
    {
        [self.usernameField resignFirstResponder];
        [self.passwordField becomeFirstResponder];
    }
    else if(textField == self.passwordField)
    {
        [self.passwordField resignFirstResponder];
        [self loginButtonClicked:nil];
    }
    return YES;
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0)
    {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",[NYMemberCenterDataManager sharedManager].loginMember.custom_service_phone]]];
    }
}

@end
